package com.sanpu.kxe.business.trade.view;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.common.view.VariantLoadingDialog;
import com.sanpu.kxe.common.view.X5WebView;
import com.sanpu.kxe.jump.jsbridge.JsBridge;
import com.sanpu.kxe.module.immersionbar.ImmersionBar;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：快捷webview支付
 * Created by 薛勇军 on 2019/3/25.
 */

public class QuickPayWebViewActivity extends BaseTitleActivity {

    @Bind(R.id.progressBar)
    ProgressBar vProgressBar;
    @Bind(R.id.titleTv)
    TextView vTitleTv;
    @Bind(R.id.webView)
    FrameLayout vViewParent;
    @Bind(R.id.titleLayout)
    LinearLayout vTitleLayout;

    private VariantLoadingDialog mLoadingDialog;

    private X5WebView mWebView;

    private JsBridge mJsBridge;

    private static int REQUESTCODE_WXPAY = 9999;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_quick_pay;
    }

    @Override
    protected void initView() {
        super.initView();
        mWebView = new X5WebView(this, null);
        mJsBridge = JsBridge.loadModule();
        showPreLoading();

        vViewParent.addView(mWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        mWebView.getSettings().setJavaScriptEnabled(true);
        WebView.setWebContentsDebuggingEnabled(true);

        String webUrl = getIntent().getStringExtra(TradeConfig.INTENT_WEB_URL);
        String postData = getIntent().getStringExtra(TradeConfig.INTENT_WEB_DATA);
        if (!TextUtils.isEmpty(webUrl)) {
            try {
                mWebView.postUrl(webUrl, postData.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mWebView.getTitle() != null) {
                    vTitleTv.setText(mWebView.getTitle());
                }
                vProgressBar.setVisibility(View.GONE);
                dismissPreLoading();
                mJsBridge.injectJs(view);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                try {
                    if (url.startsWith("weixin://wap/pay?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivityForResult(intent, REQUESTCODE_WXPAY);
                    }else {
                        return super.shouldOverrideUrlLoading(webView, url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsPrompt(WebView webView, String url, String message, String s2,
                                      JsPromptResult result) {
                mJsBridge.callJsPrompt(message, result);
                return true;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                return true;
            }

            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                super.onProgressChanged(webView, newProgress);
                if (newProgress == 100) {
                    vProgressBar.setVisibility(View.GONE);
                } else {
                    if (vProgressBar.getVisibility() == View.GONE)
                        vProgressBar.setVisibility(View.VISIBLE);
                    vProgressBar.setProgress(newProgress);
                }
            }
        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String s1, String s2, String s3, long l) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    @OnClick({R.id.leftIv, R.id.closeIv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftIv:
                onBackPressed();
                break;
            case R.id.closeIv:
                finish();
                break;
        }
    }

    /**
     * 显示加载框
     */
    public void showPreLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new VariantLoadingDialog(mContext);
        } else {
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
        }
        mLoadingDialog.show();
    }

    @Override
    protected void initImmersionBar() {
        ImmersionBar mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColorTransformEnable(true)
                .statusBarView(R.id.topView)
                .statusBarDarkFont(true, 0.5f)
                .fullScreen(false)
                .init();
    }

    /**
     * 关闭加载框
     */
    private void dismissPreLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_WXPAY) {
            finish();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        mWebView.loadUrl(intent.getData().toString());
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    protected boolean hasCommonTitle() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null)
            mWebView.destroy();
        if (mJsBridge != null)
            mJsBridge.release();
    }
}
